<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!--搜索框和添加区域 -->
      <el-row :gutter="20">
        <!-- 搜索框 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 表格列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column label="姓名" prop="username"> </el-table-column>
        <el-table-column label="邮箱" prop="email"> </el-table-column>
        <el-table-column label="电话" prop="mobile"> </el-table-column>
        <!-- 角色 -->
        <el-table-column label="角色">
          <template slot-scope="scope">
            <el-switch active-color="#13ce66" inactive-color="#dcdfe6" v-model="scope.row.mg_state" @change="userListChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <!-- c操作 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" @click="editDialogInfo(scope.row.id)"></el-button>
            <el-button type="warning" icon="el-icon-setting" @click="limitUserId(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" @click="removeUserId(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="userHandleSizeChange" @current-change="userHandleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 4, 5]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
    </el-card>

    <!-- 添加用户信息对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="34%" @close="addDialogClosed">
      <el-form :model="userForm" :rules="userFormRules" ref="userFormRef" label-width="100px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserOkay">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" width="34%">
      <el-form :model="editForm" :rules="userFormRules" ref="editUserFormRef" label-width="100px">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <!-- 手机号 -->
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserOkay">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配用户信息对话框 -->
    <el-dialog title="提示" :visible.sync="roleDialogVisible" width="34%">
      <div>
        <p>当前的用户名: {{ userRoleInfo.username }}</p>
        <p>当前的角色: {{ userRoleInfo.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="setRolesId" placeholder="请选择">
            <el-option v-for="item in setRolesListKey" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',
  data() {
    // 验证邮箱规则
    const addRulesEmail = (rule, value, callback) => {
      //  验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@(([a-zA-Z0-9_-])+\.)+([a-zA-Z0-9]{2,4})+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱'))
    }
    // 手机号验证规则
    const addRulesMobile = (rule, value, callback) => {
      const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('手机号不对,请重新输入'))
    }
    return {
      // 请求体参数
      queryInfo: {
        // 查询参数
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页显示条数
        pagesize: 5
      },
      // 用户列表数据
      userlist: [],
      // 显示总条数
      total: 0,
      // 对话框显示与隐藏初始化
      addUserDialogVisible: false,
      editDialogVisible: false,
      roleDialogVisible: false,
      // 用户信息表单数据
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 用户表单的验证规则对象
      userFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在 3到 12 个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: addRulesEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: addRulesMobile, trigger: 'blur' }
        ]
      },
      // 编辑表单数据
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      userRoleInfo: {},
      setRolesListKey: [],
      // 已选中的角色id值
      setRolesId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户管理信息请求
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户管理员列表失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 监听当前页码的数据事件  显示多少条数据
    userHandleSizeChange(pageSize) {
      this.queryInfo.pagesize = pageSize
      this.getUserList()
    },
    // 分页
    userHandleCurrentChange(pageNum) {
      this.queryInfo.pagenum = pageNum
      this.getUserList()
    },
    // 监听角色状态 事件
    async userListChange(row) {
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        return this.$message.error('设置状态失败!')
      }
      this.getUserList()
      this.$message.success('设置状态成功!')
    },
    // 添加用户 请求
    addUserOkay() {
      this.$refs.userFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请先填选项值!')
        const { data: res } = await this.$http.post('users', this.userForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户信息失败')
        this.getUserList()
        this.addUserDialogVisible = false
        this.$message.success('添加用户信息成功')
      })
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.userFormRef.resetFields()
    },
    // 点击编辑按钮弹出对话框 并查询id请求
    async editDialogInfo(id) {
      this.editDialogVisible = true
      // 查询id
      const { data: res } = await this.$http.get('users/' + id)
      this.editForm = res.data
    },
    // 编辑用户 请求
    editUserOkay() {
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请先选项值!')
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$message.error('更新用户信息失败!')
        this.getUserList()
        this.editDialogVisible = false
        this.$message.success('更新用户信息成功')
      })
    },
    // 删除用户 id 请求
    async removeUserId(id) {
      const configmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (configmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getUserList()
      this.$message.success('删除成功')
    },
    // 点击分配权限的对话框
    async limitUserId(info) {
      this.userRoleInfo = info
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.setRolesListKey = res.data
      this.roleDialogVisible = true
    },
    // 修改分配角色 请求
    async saveRoleInfo() {
      const { data: res } = await this.$http.put(`users/${this.userRoleInfo.id}/role`, { rid: this.setRolesId })
      if (res.meta.status !== 200) return this.$message.error('修改分配新角色失败')
      this.getUserList()
      this.roleDialogVisible = false
      this.$message.success('修改分配新角色成功')
    }
  }
}
</script>

<style></style>
